package com.csproj.basic.resource;

import com.codahale.metrics.annotation.Timed;
import com.csproj.basic.service.WarehouseService;
import com.csproj.basic.service.dto.WarehouseDTO;
import com.csproj.siiat.base.common.dto.BaseDTO;
import com.csproj.siiat.base.common.repository.PageableTools;
import com.csproj.system.domain.UserInfo;
import com.csproj.system.service.SysLogsService;
import com.csproj.system.service.UserInfoService;
import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * REST controller for managing Warehouse.
 */
/**
 * 企业仓储管理的resource
 *
 *  TODO action、service都秉承返回是什么资源就在那个资源的aciton、service里面写（比如查看uid=3的机构信息）
 *  TODO url定义遵循/api/gateway（服务名）/v1/资源名
 *  TODO 定义rap要理解资源的概念（比如图书馆的书和我借的书）
 *
 *  TODO action方法只负责控制调用，不处理具体业务。
 */
@RestController
@RequestMapping("/api/siiat/v1")
public class WarehouseResource {

    private final Logger log = LoggerFactory.getLogger(WarehouseResource.class);

    private static final String ENTITY_NAME = "warehouse";

    private final WarehouseService warehouseService;
    private final UserInfoService userInfoService;
    private final SysLogsService sysLogsService;

    public WarehouseResource(WarehouseService warehouseService,UserInfoService userInfoService,SysLogsService sysLogsService) {
        this.warehouseService = warehouseService;
        this.userInfoService = userInfoService;
        this.sysLogsService = sysLogsService;
    }
    /**
     * POST  /organizations : 创建机构.
     * @param warehouseDTO 机构DTO
     * @return
     * TODO 保存post方法
     * TODO 每个方面里面都要加try catch处理
     */
    @PostMapping("/warehouses")
    @Timed
    public BaseDTO createWarehouse(@Valid @RequestBody WarehouseDTO warehouseDTO){
        WarehouseDTO result = warehouseService.saveAndGetDTO(warehouseDTO);

        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_create_company","");
        return BaseDTO.createBaseDTO().setData(result);
    }

    /**
     * PUT  /organizations : 修改企业仓储.
     * @param warehouseDTO 企业仓储DTO
     * @return
     */
    @PutMapping("/warehouses/{id}")
    @Timed
    public BaseDTO updateWarehouse(@Valid @RequestBody WarehouseDTO warehouseDTO, @PathVariable String id) throws URISyntaxException {
        warehouseDTO.setId(id);
        WarehouseDTO result = warehouseService.updateAndGetDTO(warehouseDTO);

        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_update_company","");
        return BaseDTO.createBaseDTO().setData(result);
    }

    /**
     * GET  /organizations : 获取机构信息.
     * @return 机构信息
     */
    @GetMapping("/warehouses/all")
    @Timed
    public BaseDTO getAllWarehouseDTOs() {
        List<WarehouseDTO> warehouses = warehouseService.findAllAndGetDTO();
        return BaseDTO.createBaseDTO().setFieldList(warehouses);
    }

    @GetMapping("/warehouses/bysite")
    @Timed
    public BaseDTO getAllBySiteIdWarehouseDTOs() {
        String siteId = userInfoService.getCurrentUserSiteId();
        if(StringUtils.isBlank(siteId)&&siteId!="nositeID")
        {
            List<WarehouseDTO> warehouses = warehouseService.findAllAndGetDTO();
            return BaseDTO.createBaseDTO().setFieldList(warehouses);
        }
        else{
            List<WarehouseDTO> warehouses = warehouseService.findAllBySiteIdAndGetDTO(siteId);
            return BaseDTO.createBaseDTO().setFieldList(warehouses);
        }


    }
    /**
     * GET  /warehouses : 获取仓储公司信息.
     * @return 仓储公司信息
     */
    @GetMapping("/warehouses")
    @Timed
    public BaseDTO getPageWarehouseDTOs(@RequestParam(value = "pageNumber",required = false) Integer pageNum,
                                        @RequestParam(value = "pageSize",required = false) Integer pageSize,
                                        @RequestParam(value = "name",required = false) String name) {
        Pageable pageable = PageableTools.basicPage(pageNum,pageSize);
        Map<String,Object> map = new HashMap<>();
        map.put("houseName",name);
        BaseDTO result = warehouseService.findPageListAndGetDTO(map,pageable);

        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_get_company_list","");
        return result;
    }

    /**
     * GET  /warehouses/:id : 根据机构id，获取机构信息
     *
     * @param id 机构id
     * @return 机构信息
     */
    @GetMapping("/warehouses/{id}")
    @Timed
    public BaseDTO getWarehouse(@PathVariable String id) {
        WarehouseDTO warehouseDTO = warehouseService.findOneAndGetDTO(id);

        return BaseDTO.createBaseDTO().setData(warehouseDTO);
    }

    /**
     * DELETE  /warehouses/:id : 根据id，删除企业信息.
     * @param id id
     * @return
     */
    @DeleteMapping("/warehouses/{id}")
    @Timed
    public BaseDTO deleteWarehouse(@PathVariable String id) {
        warehouseService.delete(id);
        return BaseDTO.createBaseDTO().setMessage("delete_success");
    }

    /**
     * 根据企业ids，批量删除企业信息
     * @param ids ids
     * @return
     */
    @DeleteMapping("/warehouses/deleteWarehouses")
    @Timed
    public BaseDTO deleteIds(@RequestBody(required = false) String[] ids) {
        warehouseService.deleteIds(ids);
        return BaseDTO.createBaseDTO().setMessage("batch_delete_success");
    }

    /**
     * 上传文件
     * @param file file
     * @return
     */
    @PostMapping("/warehouses/uploadFile")
    @Timed
    public BaseDTO uploadFile(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        String filePath = warehouseService.uploadFile(request,file);
        Map<String,Object> map = new HashMap<>();
        map.put("url",filePath);
        return BaseDTO.createBaseDTO(map).setMessage("upload_file_success");
    }

    /**
     * PUT  /warehouses/updateSiteStatus/{id} : 修改站点使用状态
     *
     * @param warehouseDTO
     * @param id
     * @return BaseDTO
     * @throws URISyntaxException
     */
    @PutMapping("/warehouses/updateWarehouseStatus/{id}")
    @Timed
    public BaseDTO updateWarehouseStatus(HttpServletRequest request, @RequestBody(required = false) WarehouseDTO warehouseDTO, @PathVariable String id) throws URISyntaxException {
        log.debug("REST request to update UserInfo isUse : {}", warehouseDTO);
        warehouseDTO.setId(id);
        WarehouseDTO result = warehouseService.updateWarehouseStatus(warehouseDTO);

        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_update_company_status","");
        return BaseDTO.createBaseDTO(result).setMessage("update_company_success");
    }

    /**
     * 批量导入
     * @Param file
     */
    @PostMapping("/warehouses/batchImport")
    @Timed
    public BaseDTO warehouseBatchImport(MultipartFile file){
        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_update_company_batch_import","");
        return warehouseService.batchImport(file);
    }
}